const a = document.getElementsByClassName("inBox");
const i1 = document.querySelector("#i1");
const i2 = document.querySelector("#i2");
let now=0
let array = [
    [0, 0, 0,0],
    [0, 0, 0,0],
    [0, 0, 0,0],
    [0, 0, 0,0],
  ];
let red ={
  winNum:0,
  say:function(){
    alert("恭喜红方赢了")
  }
}
let black ={
  winNum:0,
  say:function(){
    alert("恭喜黑方赢了")
  }
} 
for (let i = 0; i < a.length; i++) {
a[i].addEventListener("click", () => {
let row =Math.floor(i/4)
let colum =i%4
if(array[row][colum]===0){
  now++
  console.log('now='+now);        
  if(now%2){
    a[i].innerHTML="<span style='color:red'>X</span>"
    array[row][colum]=1
    let flag=text(1)
    if(flag){
    red.winNum++
    i1.innerHTML = red.winNum
    red.say()
    start()
    }
  }
  else{
    a[i].innerHTML="<span style='color:black'>O</span>"
    array[row][colum]=2
    let flag=text(2)
    if(flag){
    black.winNum++
    i2.innerHTML = black.winNum
    black.say()
    start()
    }
  }
  if(now===16){
  alert("平局")
  start()
}

}
else{
alert("此处已下，请重新选择位置")
}        
  });
}
function text(key){
//每一行
for(let i in array){
if(array[i][0]===key&&array[i][1]===key&&array[i][2]===key&&array[i][3]===key){
  return true
}
}
//每一列
for(let i in array){
if(array[0][i]===key&&array[1][i]===key&&array[2][i]===key&&array[3][i]===key){
return true
}
}
//正斜线
for(let i in array){
if(array[0][0]===key&&array[1][1]===key&&array[2][2]===key&&array[3][3]===key){
return true
}}
//反斜线
for(let i in array){
if(array[0][3]===key&&array[1][2]===key&&array[2][1]===key&&array[3][0]===key){
return true
}}
return false
}
function start() {
  array = [
    [0, 0, 0,0],
    [0, 0, 0,0],
    [0, 0, 0,0],
    [0, 0, 0,0],
  ];
  now = 0;
  for (let i = 0; i < a.length; i++) {
    a[i].innerHTML = "";
  }
}